package com.pengyang.netty.demo.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.pengyang.netty.demo.pojo.IMMessage;
import com.pengyang.netty.demo.pojo.SelfDefinedProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;  
  
//用于读取客户端发来的信息  
public class ClientHandler extends ChannelInboundHandlerAdapter implements IMClientConfig {  
  
	private ChannelHandlerContext ctx;
	
	private IMMessage msg;
	 
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用户["+ UID + "]成功连接服务器");
        this.ctx = ctx;
 
        //通道建立时发送认证消息给服务器
//        IMMessage message = new IMMessage(
//                1,
//                TYPE_MSG_AUTH.value(),
//                1,
//                null
//                );
        sendMsg(msg);
    }  
  
	public  boolean sendMsg(IMMessage msg) throws IOException {
        boolean result = msg.getMsg().equals("quit") ? false:true;
        if(result){
            /*if(msg.getMsgType() != MessageType.TYPE_AUTH.value()){
                System.out.println("client[" + msg.getUid() + "]:" + msg.getMsg());
            }*/
            ctx.writeAndFlush(msg);
        }
        return result;
    }
	
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        IMMessage m = (IMMessage)msg;
        System.out.println("receive[" + m.getUid() + "]:" + m.getMsg());
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("与服务器断开连接：" + cause.getMessage());
        ctx.close();
    }

	public IMMessage getMsg() {
		return msg;
	}

	public void setMsg(IMMessage msg) {
		this.msg = msg;
	}

}  